package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amazon.spapi.model.sellers.GetMarketplaceParticipationsResponse;
import com.amazon.spapi.model.sellers.Marketplace;
import com.amazon.spapi.model.sellers.MarketplaceParticipation;
import com.amazon.spapi.model.sellers.MarketplaceParticipationList;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.entity.ShopAuthorization;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.SysRegion;
import com.fowo.api.entity.Warehouse;
import com.fowo.api.model.shop.authorization.ShopAuthorizationVo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSellerAuthAction;
import com.fowo.api.model.shop.info.ShopInfoVo;
import com.fowo.api.model.warehouse.WarehouseVo;
import com.fowo.api.service.impl.ShopAuthorizationServiceImpl;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.SysRegionServiceImpl;
import com.fowo.api.service.impl.WarehouseServiceImpl;
import com.fowo.api.syncAmazon.api.SellersService;
import com.fowo.api.user.model.JwtUserInfo;
import liquibase.pro.packaged.E;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ShopInfoSellerAuthActionImpl {

    private static final String PATH = "https://sellercentral.amazon.com/apps/authorize/consent";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ShopAuthorizationServiceImpl shopAuthorizationService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private AmazonService amazonService;
    @Resource
    private SysRegionServiceImpl regionService;
    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private Common common;
    @Resource
    private SellersService sellersService;
    @Resource
    private WarehouseServiceImpl warehouseService;

//    @Override
    public void run(Long id) throws Exception {
        StringBuffer url = new StringBuffer(PATH);
        url.append("?").append("application_id=amzn1.sp.solution.47ad2e87-cf5f-41cb-968f-cda83fcc1e32")
                .append("&redirect_uri=https://wmdemo.hibcp.com/api/amazon/callback")
                .append("&state=").append(id)
                .append("&version=beta");
//        url.toString();
        restTemplate.getForObject(url.toString(),Map.class);
    }

    public void loginOauth(String amazon_callback_uri,String amazon_state,String version,String selling_partner_id){
        restTemplate.getForObject(amazon_callback_uri+"?amazon_state="+amazon_state+"&state="+selling_partner_id+"&version="+version,Map.class);
    }

    public void getRefreshToken(String spapi_oauth_code,String state,String selling_partner_id) throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        String authData = state.replace("ALI_AMZ11_", "");
        String[] strings = authData.split("__");

        ShopAuthorizationVo shopAuthorizationVo;
        if(strings.length == 3){
            shopAuthorizationVo = new ShopAuthorizationVo();
            shopAuthorizationVo.setName(strings[0]);
            shopAuthorizationVo.setCountry(Long.valueOf(strings[1]));
            shopAuthorizationVo.setRegions(strings[2]);
        }else {
            shopAuthorizationVo = shopAuthorizationService.getVoById(Long.valueOf(strings[0]));
//            shopAuthorizationVo.setName(strings[1]);
            shopAuthorizationVo.setCountry(Long.valueOf(strings[2]));
            shopAuthorizationVo.setRegions(strings[3]);
        }

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        headers.add("Host","api.amazon.com");
        Map<String,Object> params = new HashMap<>();
        params.put("grant_type","authorization_code");//authorization_code
        params.put("code",spapi_oauth_code);
        params.put("client_id",common.getAuthoritySimpleFactory(entityAuthority, "clientId"));
        params.put("client_secret",common.getAuthoritySimpleFactory(entityAuthority, "clientSecret"));
        HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.toJsonStr(params), headers);
        log.info("授权请求参数：{}{}", JSONUtil.toJsonStr(headers),JSONUtil.toJsonStr(params));

        String refreshToken = "";
        try{
//            ResponseEntity<Map> response = restTemplate.postForEntity("https://api.amazon.com/auth/o2/token", httpEntity, Map.class);
            ResponseEntity<Map> response = restTemplate.postForEntity(common.getAuthoritySimpleFactory(entityAuthority, "endpoint"), httpEntity, Map.class);

            Map body = response.getBody();
            log.info("授权返回参数：{}",JSONUtil.toJsonStr(body));
            JSONObject jsonObject = JSONUtil.parseObj(body);
            refreshToken = jsonObject.getStr("refresh_token");

            shopAuthorizationVo.setSellerId(selling_partner_id);
            shopAuthorizationVo.setStatus("SQ01");
        }catch (Exception e){
            shopAuthorizationVo.setStatus("SQ02");
        }

        if(shopAuthorizationVo.getId() == null){
            createShopAuthorizationVo(shopAuthorizationVo);
        }else {
            shopAuthorizationService.updateById(shopAuthorizationVo);
        }
        updateShop(shopAuthorizationVo,refreshToken);
    }

    /**
     * 保存店铺授权信息
     * @param shopAuthorizationVo
     * @param refreshToken
     */
    public void updateShop(ShopAuthorizationVo shopAuthorizationVo,String refreshToken) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        ShopInfo shopInfo;
        Date errorDate = shopAuthorizationVo.getStatus().equals("SQ01") ? null : new Date();
        List<ShopInfo> shopInfoList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getParentShopAuthorization,shopAuthorizationVo.getId()));
        for(String regionId : shopAuthorizationVo.getRegions().split(",")){
            final SysRegion region = regionService.getById(Long.valueOf(regionId));
            shopInfo = shopInfoList.stream()
                    .filter(s -> s.getMid().equals(region.getId()) && s.getMarketplaceId().equals(region.getMarketplaceId()))
                    .findAny()
                    .orElse(null);
            if(null == shopInfo){
                final GetMarketplaceParticipationsResponse marketplaceParticipations = sellersService.getMarketplaceParticipations(refreshToken, region.getEndpoint(), region.getRegion());
                final Marketplace marketplace = marketplaceParticipations.getPayload().stream().map(m -> m.getMarketplace()).filter(m -> m.getId().equals(region.getMarketplaceId())).findFirst().orElse(null);
                if (currentUser != null) {
                    shopInfo.setCreateUser(currentUser.getUserId());
                    shopInfo.setLastUpdateUser(currentUser.getUserId());
                }
                shopInfo = new ShopInfoVo();
                shopInfo.setCreateTime(new Date());
                shopInfo.setLastUpdateTime(new Date());
                shopInfo.setParentShopAuthorization(shopAuthorizationVo.getId());
                shopInfo.setShopName(shopAuthorizationVo.getName()+"-"+region.getCode());
                shopInfo.setCountry(region.getName());
                shopInfo.setSellerAuthStatus(shopAuthorizationVo.getStatus());
                shopInfo.setAuthTime(new Date());
                shopInfo.setRefreshToken(refreshToken);
                shopInfo.setPlatform("Amazon");
                shopInfo.setRegion(region.getCode());
                shopInfo.setMid(region.getId());
                shopInfo.setEndpoint(region.getEndpoint());
                shopInfo.setMarketplaceId(region.getMarketplaceId());
                shopInfo.setAwsRegion(region.getRegion());
                shopInfo.setErrorAuthTime(errorDate);
                shopInfo.setSellerId(shopAuthorizationVo.getSellerId());
                shopInfo.setHasAdsSetting(false);
                shopInfo.setMarketplaceName(null == marketplace ? "" : marketplace.getName());
                shopInfoService.save(shopInfo);
                //添加对应仓库
                createWarehouse(shopInfo,region);
            }else{
                shopInfoList.remove(shopInfo);
                if (currentUser != null) {
                    shopInfo.setLastUpdateUser(currentUser.getUserId());
                }
                shopInfo.setLastUpdateTime(new Date());
                shopInfo.setSellerAuthStatus(shopAuthorizationVo.getStatus());
                shopInfo.setRefreshToken(refreshToken);
                shopInfo.setUpdateAuthTime(new Date());
                shopInfo.setErrorAuthTime(errorDate);
                shopInfo.setRegion(region.getCode());
                shopInfo.setMid(region.getId());
                shopInfo.setEndpoint(region.getEndpoint());
                shopInfo.setMarketplaceId(region.getMarketplaceId());
                shopInfo.setAwsRegion(region.getRegion());
                shopInfoService.updateById(shopInfo);
            }
        }
        if(CollectionUtil.isNotEmpty(shopInfoList)){
            shopInfoService.removeBatchByIds(shopInfoList);
        }
    }

    public void createWarehouse(ShopInfo shopInfo,SysRegion region){
        Warehouse model = new Warehouse();
        model.setName(shopInfo.getShopName()+region.getName()+"仓");
        model.setWidType("2");
        model.setSid(shopInfo.getId());
        model.setCreateTime(new Date());
        model.setLastUpdateTime(new Date());
        warehouseService.save(model);
    }

    public String createAuthorization(ShopAuthorizationVo model){
//        JSONUtil.toJsonStr(model);
        String state = model.getName()+"__"+model.getCountry()+"__"+model.getRegions();
        return getAuthUrl(state);
    }

    public Long createShopAuthorizationVo(ShopAuthorizationVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        ShopAuthorization entity = new ShopAuthorization();
        BeanUtils.copyProperties(model, entity);
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (shopAuthorizationService.save(entity)) {
            model.setId(entity.getId());
            return entity.getId();
        }
        throw new Exception("店铺授权保存失败");
    }

    public String updateAuthorization(ShopAuthorizationVo model) throws Exception {
//        shopAuthorizationService.update(model);
        String state = model.getId()+"__"+model.getName()+"__"+model.getCountry()+"__"+model.getRegions();
        return getAuthUrl(state);
    }

    /**
     * 获取授权地址
     * @param state
     * @return
     */
    public String getAuthUrl(String state) {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
//        final SysRegion region = regionService.getById(regionId);
        String applicationId = common.getAuthoritySimpleFactory(entityAuthority, "applicationId");

        StringBuffer url = new StringBuffer(PATH);
        url.append("?").append("application_id=").append(applicationId)
                .append("&redirect_uri=").append(common.getAuthoritySimpleFactory(entityAuthority, "redirectUri"))
//                .append("&redirect_uri=").append("https://www.baidu.com")
                .append("&state=ALI_AMZ11_").append(state)
                .append("&version=beta");
//        url.append("?application_id="+applicationId)
//                .append("&state=ALI_AMZ11_").append(state);
        return url.toString();
    }
}
